import Vue from "vue";
import Router from "vue-router";
// 引入login组件
import Login from "@/components/login/login.vue";
import Home from "@/components/home/home.vue";
import Home1 from "@/components/home/home1.vue";
import Users from "@/components/users/users.vue";
import Permissions from "@/components/permissions/permissions.vue";
import Role from "@/components/permissions/role.vue";
import Goods from "@/components/goods/goods.vue";
import GoodsAdd from "@/components/goods/goodsadd.vue";
import Cateparams from "@/components/goods/cateparams.vue";
import Goodscate from "@/components/goods/goodscate.vue";
import { Message } from "element-ui";

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: "/",
      name: "index",
      redirect: { name: "login" }
    },
    {
      path: "/login",
      name: "login",
      component: Login
    },
    // {
    //   path: "/home",
    //   name: "home",
    //   component: Home,
    //   children: [
    //     {
    //       path: "/users",
    //       name: "users",
    //       component: Users
    //     },
    //     { path: "/permissions", name: "permissions", component: Permissions },
    //     { path: "/role", name: "role", component: Role },
    //     { path: "/goods", name: "goods", component: Goods }
    //   ]
    // },
    {
      path: "/home1",
      name: "home1",
      component: Home1,
      children: [
        {
          path: "/users",
          name: "users",
          component: Users
        },
        { path: "/permissions", name: "permissions", component: Permissions },
        { path: "/role", name: "role", component: Role },
        { path: "/goods", name: "goods", component: Goods },
        { path: "/goodsadd", name: "goodsadd", component: GoodsAdd },
        { path: "/cateparams", name: "cateparams", component: Cateparams },
        { path: "/goodscate", name: "goodscate", component: Goodscate }
      ]
    }
  ]
});

// 路由守卫 在路由配置生效之前执行,所以我们就不用在vue界面中在判断是否有token
router.beforeEach((to, from, next) => {
  // 如果要去的是登录 -> next()
  if (to.path === "/login") {
    next();
  } else {
    // 如果要去的不是登录
    // 判断token
    const token = localStorage.getItem("token");
    if (!token) {
      // 如果token没有 ---->login
      // this.$router.push({name:'login'})
      Message.warning("请先登录");
      router.push({ name: "login" });
      return;
    }
    // 如果有 -------> 继续渲染组件 next()
    next();
  }
});

export default router;
